let dao = require("./../dao/dao");
let gameInfo = require('./../class/game').getInstand;
let http = require('http');
let querystring = require("querystring");
let Buffer = require("buffer").Buffer;
let log = require("./../../util/loginfo").getInstand;
let withdrawDao = require('./../dao/withdraw_dao');
const { v4: uuidv4 } = require('uuid');

var withdrawal_api = function (options) {
    options = options || '';
    var _socket = options._socket;
    var _info = options._info;

    let userInfo = {
        sendUserId: _socket.userId,
        sendCoin: -_info.coin,
        change_type: 4,
        diamond: 0
    };
    
    let userScore = 0;
    var self = this;
    new Promise(function (resolve, reject) {
        dao.getUserCoinById(_socket.userId, function(state, score){
            if (state) {
                userScore = score;
                resolve(1);
            } else {
                //玩家不存在
                _socket.emit('withdraw_applyResult', {ResultCode: 1});
                log.err("user is not existed ! user " + _socket.userId);
                reject(0);
            }
        })
    }).then(function (value) {
        //判断玩家分数够不够
        if (userScore < _info.coin) {
            //当前余额不足
            _socket.emit('withdraw_applyResult', {ResultCode: 3});
            log.err("user coin is not enough! user " + _socket.userId + " score ", userScore + " should withdraw coin " + _info.coin);
            return;
        }

        //1.获取银行卡信息
        dao.getBank(_socket.userId, function (Result, row) {
            if (!Result) {
                //未找到银行卡
                _socket.emit('withdraw_applyResult', {ResultCode: 2});
                log.err("system not find user bank card, user " + _socket.userId);
                return;
            }

            //2.生成订单入库
            let orderInfo = {
                orderNO: uuidv4(),
                userId: _socket.userId,
                changeGold: _info.coin,
                orderStatus: 1, //未处理
                type: 4, //提现
                beforeGold: userScore,
                afterGold: userScore - _info.coin 
            }
            withdrawDao.InsertNewOrder(orderInfo, function(state) {
                if (state == 0) {
                    _socket.emit('withdraw_applyResult', {ResultCode: 4}); //生成订单失败
                    log.err("withdraw failed for not insert new order! user " + _socket.userId);
                    return;
                }

                //3.预扣金币
                gameInfo.GameBalance(userInfo, (result) => {
                    let bRes = JSON.parse(result);
                    if (bRes.status == 1) { //扣币失败
                        _socket.emit('withdraw_applyResult', {ResultCode: 5}); 
                        log.err("withdraw failed for GameBalanceSub failed! user " + _socket.userId);
                        return;
                    }
                    log.info("withdraw user "  + _socket.userId  + " success substract gold "  + _info.coin  + " current score "  + userScore);

                    //4.申请提现
                    self.postWeb(row[0], _info.coin, orderInfo.orderNO, (code) => {
                        if (code == 0){
                            //5.成功则返回前端消息, 失败则金币回滚后返回前端消息
                            userInfo.sendCoin = _info.coin;
                            gameInfo.GameBalance(userInfo, function(state){
                                _socket.emit('withdraw_applyResult', {ResultCode: 6}); //提现失败
                                if (state==0){
                                    log.err("withdraw rollback failed, please check manually! user "  + _socket.userId);
                                    return;
                                }
                                orderInfo.orderStatus = 3; //已回滚状态
                                orderInfo.afterGold = userScore;
                                withdrawDao.UpdateOrder(orderInfo, function(state) {
                                    if (!state) { log.err("UpdateOrder failed user " + _socket.userId);}
                                });
                                log.err("withdraw failed for postWeb failed! user " + _socket.userId);
                            });
                            return;
                        }
                        orderInfo.orderStatus = 2; //已成功状态
                        withdrawDao.UpdateOrder(orderInfo, function(state) {
                            if (!state) { log.err("UpdateOrder failed user " + _socket.userId);}
                        });
                        _socket.emit('withdraw_applyResult', {ResultCode: 0}); //提现成功
                        log.info("withdraw success for postWeb user " + _socket.userId);
                    });
                });
            });
        });
    }).catch(function (err) {
        log.err("with draw error == ", err);
    });


    this.postWeb = function (_info, _money, orderNO, cb) {
        try {
            var post_data = {
                bank_number: _info.account,
                name: _info.name,
                open: _info.bankType,
                money: _money,
                id: _info.userId,
                orderNO: orderNO
            };//这是需要提交的数据
    
            var content = encodeURI(querystring.stringify(post_data));
            var postdata = `/uid/${_info.userId}/amount/${_money}/receive_name/${_info.name}/receive_account/${_info.account}/orderNO/${orderNO}`;
            var options = {
                hostname: 'admin.1topgames.com',//107.6.242.33
                port: 80,  //9999注意端口号 可以忽略不写 写一定写对
                path: encodeURI('/index.php/api/pay/wowPayBehalf' + postdata),
                method: 'GET',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    // 'Content-Length': content.length,
                }
            };

            var req = http.request(options, function (res) {
                var size = 0;
                var chunks = [];
    
                res.on('data', function (chunk) {
                    size += chunk.length;
                    chunks.push(chunk);
                });
    
                res.on('end', function () {
                    var data = Buffer.concat(chunks, size);
                    try {
                        let info = JSON.parse(data.toString());
                        log.info("post web return code == "  + info.code)
                        log.info("data json == " + data.toString());
                        cb(info.code);
                    } catch (e) {
                        log.err("postWeb error == "  + e);
                        cb(0);
                    }
                });
            });
    
            req.on('error', function (e) {
                log.err('problem with request: '  + e.message);
                cb(0);
            });
    
            // write data to request body
            req.write(content);
            req.end();
        } catch (error) {
            log.err("postWeb error == ", error);
            cb(0);
        }
    };

    this.postData = function (_info, _money, cb) {
        var post_data = {
            bank_number: _info.account,
            name: _info.name,
            open: _info.bankType,
            money: _money,
            id: _info.userId,

        };//这是需要提交的数据

        var content = querystring.stringify(post_data);
        // var postdata = "bank_number=" + _info.account + "&name=" + _info.name + "&open=" + _info.bankType + "&money=" + _money + "&id=" + _info.userId;

        var options = {
            hostname: 'admin.1topgames.com',
            port: 80,  //注意端口号 可以忽略不写 写一定写对
            path: '/index.php/api/user/exchange',
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'Content-Length': content.length,
            }
        };

        var req = http.request(options, function (res) {
            // res.setEncoding('utf8');
            var size = 0;
            var chunks = [];

            res.on('data', function (chunk) {
                size += chunk.length;
                chunks.push(chunk);
            });

            res.on('end', function () {
                var data = Buffer.concat(chunks, size);
                try {
                    log.info(data.toString());
                    let info = JSON.parse(data.toString());
                    cb(info.code);
                } catch (e) {
                    log.info(e);
                }
            });
        });

        req.on('error', function (e) {
            log.info('problem with request: ' + e.message);
        });

        // write data to request body
        req.write(content);

        req.end();
    };
};

module.exports = withdrawal_api;